package org.nerve.okhttp3.facebook;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.nerve.okhttp3.HtmlStringUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * org.nerve.okhttp3.facebook
 * Created by zengxm on 2016/7/28.
 */
public class ProfileTimeLine {

	public final static String WRAPPER="userContentWrapper";
	public final static String PICK_START="<div class=\\\"_5pcb _4b0l\\\">";
	public final static String PICK_END="<\\/form><\\/div><\\/div><\\/div><\\/div><\\/div>";

	private int count;              //动态条数
	private List<String> contents = new ArrayList<>();  //动态文本列表

	private ProfileTimeLine(){}

	public void addContent(String c){
		contents.add(c);
	}
	public int getCount() {
		return count;
	}

	public ProfileTimeLine setCount(int count) {
		this.count = count;
		return this;
	}

	public List<String> getContents() {
		return contents;
	}

	public ProfileTimeLine setContents(List<String> contents) {
		this.contents = contents;
		return this;
	}

	public static ProfileTimeLine parse(File file) throws IOException {
		return parse(new String(Files.readAllBytes(file.toPath()), Charset.forName("utf-8")));
	}

	public static ProfileTimeLine parse(String content){
		//先对 \" 进行替换成 "
		if(content==null) throw new NullPointerException("content is null! Could not parse!");
		System.out.println("string length="+content.length());

		final String html = content.replace("\\\"","\"").replace("\\/","/");

		ProfileTimeLine p=new ProfileTimeLine();
		p.count = HtmlStringUtil.count(html, WRAPPER);     //判断有多少则动态

		//利用Jsoup进行html解析
		Document doc=Jsoup.parse(html);

		Elements wrappers=doc.select("."+WRAPPER);
		wrappers.forEach(e->{
			StringBuilder sb=new StringBuilder();

			//获取动态发布时间
			Elements timeE=e.getElementsByTag("abbr");
			if(!timeE.isEmpty())
				sb.append(timeE.first().attr("title")+"\t");

			//获取动态内容
			Elements ce=e.select("._3x-2");
			if(!ce.isEmpty())
				sb.append(ce.first().text());

			p.addContent(sb.toString());
		});
		return p;
	}

	/**
	 * 从最原始的Http Response（来自Ajax请求）中抽取包含了动态数据的html代码
	 * @param html
	 * @return
	 */
	public static String pickFromOriginHtml(String html){
		return pickFromOriginHtml(html, PICK_START, PICK_END);
	}

	public static String pickFromOriginHtml(String html,String startStr, String endStr){
		if(html==null) return null;

		/*
		抽取方式1：截取字符串的方式
			1.找到startStr 的位置
			2.找到endStr 的位置
			3.返回上述两个位置中的文字即可

		抽取方式2：使用正则表达式进行匹配

		这里用的是方式1
		 */
		int startIndex=html.indexOf(startStr);
		int endIndex=html.indexOf(endStr);

		if(startIndex>-1 && endIndex>-1 && endIndex>startIndex)
			return html.substring(startIndex, endIndex+endStr.length());

		return html;
	}
}
